/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.controller.company;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.controller.CommonTreeController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.result.DirectJsonResult;
import com.je.common.base.service.CommonTreeService;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.plugins.pagination.Page;
import com.je.rbac.annotation.ControllerAuditLog;
import com.je.rbac.exception.CompanyException;
import com.je.rbac.rpc.CompanyRpcService;
import com.je.rbac.service.IconType;
import com.je.rbac.service.company.RbacCompanyService;
import com.je.rbac.service.company.RbacDepartmentService;
import com.je.rbac.service.remove.CompanyDeptMoveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 公司管理
 */
@RestController
@RequestMapping(value = "/je/rbac/cloud/company")
public class RbacCompanyController extends CommonTreeController {

    @Autowired
    private RbacCompanyService rbacCompanyService;
    @Autowired
    private CompanyRpcService companyRpcService;
    @Autowired
    private CommonTreeService commonTreeService;
    @Autowired
    private RbacDepartmentService rbacDepartmentService;
    @Autowired
    private CompanyDeptMoveService companyDeptMoveService;

    /***
     * 加载公司列表
     * @param param
     * @param request
     * @return
     */
    @Override
    @RequestMapping( value = {"/load"}, method = {RequestMethod.POST}, produces = {"application/json; charset=utf-8"})
    @ControllerAuditLog(moduleName = "公司管理", operateTypeCode = "loadCompany", operateTypeName = "查看公司", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult load(BaseMethodArgument param, HttpServletRequest request) {
        Page page = this.manager.load(param, request);
        return page == null ? BaseRespResult.successResultPage(Lists.newArrayList(), 0L) : BaseRespResult.successResultPage(page.getRecords(), (long)page.getTotal());
    }


    /***
     * 保存
     * @param param
     * @param request
     * @return
     * @throws CompanyException
     */
    @Override
    @RequestMapping(value = "/doSave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "公司管理", operateTypeCode = "saveCompany", operateTypeName = "保存公司", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult doSave(BaseMethodArgument param, HttpServletRequest request) throws CompanyException{
            //获取新增数据
            DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
            if(!rbacCompanyService.checkCompanyNameUnique(dynaBean)){
                return BaseRespResult.errorResult("公司名称重复，请修改！");
            }
            if(!rbacCompanyService.checkCompanyCodeUnique(dynaBean)){
                return BaseRespResult.errorResult("公司编码重复，请修改！");
            }
        try {
            DynaBean savedBean = rbacCompanyService.doSave(dynaBean);
            JSONTreeNode node = commonTreeService.buildSingleTreeNode(savedBean);
            Map<String, Object> result = new HashMap<>();
            result.put("dynaBean", savedBean.getValues());
            result.put("node", node);
            return BaseRespResult.successResult(result);
        } catch (CompanyException e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
    }

    /***
     * 修改
     * @param param
     * @param request
     * @return
     * @throws CompanyException
     */
    @Override
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "公司管理", operateTypeCode = "updateCompany", operateTypeName = "更新公司", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult doUpdate(BaseMethodArgument param, HttpServletRequest request){
            // 获取修改数据
            DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
            if(!rbacCompanyService.checkCompanyNameUnique(dynaBean)){
                return BaseRespResult.errorResult("公司名称重复，请修改！");
            }
            if(!rbacCompanyService.checkCompanyCodeUnique(dynaBean)){
                return BaseRespResult.errorResult("公司编码重复，请修改！");
            }
        try {
            rbacCompanyService.checkCompanyLevelCode(dynaBean);
            rbacCompanyService.updateCompanyName(dynaBean);
            DynaBean updatedBean = manager.doUpdate(param, request);
            if("GROUP_COMPANY".equals(updatedBean.getStr("COMPANY_LEVEL_CODE")) && IconType.TCONTYPE_COMPANY.getVal().equals(updatedBean.getStr("COMPANY_ICON"))){
                rbacCompanyService.updateCompanyIcon(updatedBean);
            }

            JSONTreeNode node = commonTreeService.buildSingleTreeNode(updatedBean);
            Map<String, Object> result = new HashMap<>();
            result.put("dynaBean", updatedBean.getValues());
            result.put("node", node);
            return BaseRespResult.successResult(result);
        }  catch (CompanyException e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
    }

    /**
     * 启用
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/enable"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "公司管理", operateTypeCode = "enableCompany", operateTypeName = "启用公司", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult enable(HttpServletRequest request) {
        String companyIds = getStringParameter(request,"companyIds");
        if(Strings.isNullOrEmpty(companyIds)){
            return BaseRespResult.errorResult("请选择需要启用的公司！");
        }
        try {
            if(rbacCompanyService.findGroupCompanyStatus(companyIds)){
                companyRpcService.enableCompany(companyIds);
            }
        }catch (CompanyException e){
            return BaseRespResult.errorResult(e.getMessage());
        }

        return BaseRespResult.successResult("启用成功！");
    }

    /**
     * 禁用
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/disable"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "公司管理", operateTypeCode = "disableCompany", operateTypeName = "禁用公司", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult disable(HttpServletRequest request) {
        String companyIds = getStringParameter(request,"companyIds");
        if(Strings.isNullOrEmpty(companyIds)){
            return BaseRespResult.errorResult("请选择需要禁用的公司！");
        }
        companyRpcService.disableCompany(companyIds);
        return BaseRespResult.successResult("禁用成功！");
    }

    /**
     * 删除
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/remove"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "公司管理", operateTypeCode = "removeCompany", operateTypeName = "移除公司", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult remove(HttpServletRequest request) throws CompanyException{
        String ids = getStringParameter(request,"ids");
        String withDeptAndUsers = getStringParameter(request,"withType");
        if(Strings.isNullOrEmpty(ids)){
            return BaseRespResult.errorResult("请选择要删除的公司！");
        }
        if("0".equals(withDeptAndUsers) && !rbacCompanyService.checkChildCompany(ids)){
            return BaseRespResult.errorResult("该公司存在下级公司，不允许删除！");
        }
        if("0".equals(withDeptAndUsers) && !rbacCompanyService.checkChildDept(ids)){
            return BaseRespResult.errorResult("该公司存在下级部门，不允许删除！");
        }
        long count = companyRpcService.removeCompany(ids,"1".equals(withDeptAndUsers));
        if(count<=0){
            return BaseRespResult.errorResult("删除失败！");
        }
        return BaseRespResult.successResult("删除成功！");
    }

    /**
     * 加载公司树
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/loadCompanyTree"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult loadCompanyTree(HttpServletRequest request) {
        String companyIds = getStringParameter(request,"companyIds");
        JSONTreeNode rootNode;
        if(Strings.isNullOrEmpty(companyIds)){
            rootNode = companyRpcService.buildCompanyTree();
        }else{
            rootNode = companyRpcService.buildCompanyTree(companyIds.split(","));
        }
        return BaseRespResult.successResult(rootNode);
    }

    /**
     * 移动公司
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/moveCompany"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "公司管理", operateTypeCode = "moveCompany", operateTypeName = "移动公司", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult moveCompany(HttpServletRequest request) {
        String tableCode = getStringParameter(request, "tableCode");
        if (Strings.isNullOrEmpty(tableCode)) {
            return BaseRespResult.errorResult("请选择要移动数据的表编码！");
        }
        String id = getStringParameter(request, "id");
        if (Strings.isNullOrEmpty(id)) {
            return BaseRespResult.errorResult("请选择要移动数据的id！");
        }
        String toId = getStringParameter(request, "toId");
        if (Strings.isNullOrEmpty(toId)) {
            return BaseRespResult.errorResult("请选择要移动的目标数据id！");
        }
        String place = getStringParameter(request, "place");
        if (Strings.isNullOrEmpty(place)) {
            return BaseRespResult.errorResult("请选择要移动的数据位置！");
        }
        try {
            if(tableCode.equals("JE_RBAC_COMPANY")){
                DynaBean dynaBean = new DynaBean(tableCode,false);
                dynaBean.put("id",id);
                dynaBean.put("toId",toId);
                dynaBean.put("place",place);
                companyDeptMoveService.move(dynaBean);
            }
        } catch (CompanyException e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
        return BaseRespResult.successResult("操作成功！");
    }

    @Override
    @RequestMapping(value = "/getTree", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult getTree(BaseMethodArgument param, HttpServletRequest request) {
        JSONTreeNode tree = rbacDepartmentService.buildForbiddenCompanyTreeData(true,false);
        if (tree != null) {
            return BaseRespResult.successResult(DirectJsonResult.buildObjectResult(tree));
        } else {
            return BaseRespResult.successResult(DirectJsonResult.buildObjectResult("{}"));
        }
    }

}
